package de.gameduell.framework.facebook.communication {
	import de.gameduell.framework.debug.Debug;
	import de.gameduell.framework.queue.ActionEvent;
	import de.gameduell.framework.queue.GDActionQueue;
	import de.gameduell.framework.queue.IGDAction;
	import de.polygonal.ds.Set;

	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;

	public class ServiceLayerRequestAction extends EventDispatcher implements IGDAction {
		
		private static const actionQueue:GDActionQueue = new GDActionQueue();
		
		private static var openRequests:Set = new Set();
		private static var _safeRequests:Set = new Set();
		
		
		private var _description:String;
		private var loader:URLLoader;
		private var request:URLRequest;
		private var active:Boolean = true;

		public function ServiceLayerRequestAction(aLoader:URLLoader, aRequest:URLRequest, invokeNow:Boolean = false, aDescription:String = "ServiceLayerRequestAction") {
			_description = aDescription;
			loader = aLoader;
			request = aRequest;
			loader.addEventListener(Event.COMPLETE, onCallComplete);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onCallComplete);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onCallComplete);
			
			if(invokeNow) {
				invoke();
			}	
		}
		
		public static function set safeRequests(aList:Array):void {
			for each(var desc:String in aList){
				_safeRequests.set(desc);
			}
		}

		public function compute():void {
			loader.load(request);
		}

		public function invoke():void {
			if(!openRequests.contains(_description) || _safeRequests.contains(_description)){
				openRequests.set(_description);
				actionQueue.add(this);
			}else{
				Debug.trace("ServiceLayerRequestAction::invoke: DROPPED action - already in queue ..." + _description, Debug.CONNECTION);
			}
		}

		private function onCallComplete(event:Event):void {
			Debug.trace("ServiceLayerRequestAction::onCallComplete: " + _description, Debug.CONNECTION);
			loader.removeEventListener(Event.COMPLETE, onCallComplete);
			loader.removeEventListener(IOErrorEvent.IO_ERROR, onCallComplete);
			loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onCallComplete);
			if(active){
				dispatchEvent(new ActionEvent(ActionEvent.DONE));
			}
			openRequests.remove(_description);
			active = false;
		}

		public function get description():String {
			return _description;
		}
	}
}
